package com.module.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.system.auth.AuthUtil;
import com.system.comm.utils.FrameJsonUtil;
import com.system.handler.model.ResponseCode;
import com.system.handler.model.ResponseFrame;

/**
 * 开放平台的拦截器
 * @author duanbin
 * @date 2016-5-16 下午10:09:43
 * @version V1.0.0
 */
public class AuthSecurityInterceptor implements HandlerInterceptor {
	
	private static final Logger LOGGER = Logger.getLogger(AuthSecurityInterceptor.class);
	
	private List<String> uncheckUrls; 

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
	}

	/**
	 * 在Controller方法前进行拦截
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		//免拦截检查
		String requestUrl = request.getRequestURI();
		if(uncheckUrls != null && uncheckUrls.contains(requestUrl)){ 
			return true;
		}
		
		//校验客户端提交的client_sercret是否正确
		String clientId = request.getParameter("clientId");
		String sign = request.getParameter("sign");
		String time = request.getParameter("time");

		//LOGGER.info("{ clientId:" + clientId + ", time:" + time + ", sign:" + sign + " } 请求地址: " + request.getRequestURI());
		
		if(!AuthUtil.authVerify(clientId, time, sign)) {
			LOGGER.error("非法请求(abnormal signature): { clientId:" + clientId + ", time:" + time + ", sign:" + sign + " } 请求地址: " + request.getRequestURI());
			ResponseFrame frame = new ResponseFrame();
			frame.setCode(ResponseCode.ABNORMAL_SIGNATURE.getCode());
			frame.setMessage(ResponseCode.ABNORMAL_SIGNATURE.getMessage());
			response.getWriter().print(FrameJsonUtil.toString(frame));
			return false;
		}
		return true;
	}
	
	public List<String> getUncheckUrls() {
		return uncheckUrls;
	}

	public void setUncheckUrls(List<String> uncheckUrls) {
		this.uncheckUrls = uncheckUrls;
	}
}